package com.ctsi.auth.integration.authenticator.impl;

import com.ctsi.auth.integration.IntegrationAuthentication;
import com.ctsi.auth.vcc.manager.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Component;

/**
 * @author zhangjw
 * @className ImageCodeIntegrationAuthenticator
 * @description 图片验证码登陆
 * @date 2019/2/21 14:35
 **/
@Component
public class ImageCodeIntegrationAuthenticator extends UsernamePasswordAuthenticator {
    /**
     * 认证类型
     */
    private final static String IMG_AUTH_TYPE = "image";

    @Autowired
    private VerificationCodeService verificationCodeService;

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) throws OAuth2Exception{
        String vcToken = integrationAuthentication.getAuthParameter("vc_token");
        String vcCode = integrationAuthentication.getAuthParameter("vc_code");
        boolean result = verificationCodeService.validate(vcToken,vcCode,null);
        /**
         * 验证码有效期内只能使用一次
         */
        verificationCodeService.evictCache(vcToken,null);
        if (!result) {
            throw new OAuth2Exception("验证码错误");
        }
    }

    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return IMG_AUTH_TYPE.equals(integrationAuthentication.getAuthType());
    }

}
